//
//  CYCloudSyn.m
//  CreditAddressBook
//
//  Created by LE on 15/12/9.
//  Copyright © 2015年 Lee. All rights reserved.
//

#import "CYCloudSyn.h"
#import "CircleView.h"
#import "NSString+Extension.h"
#import "CYUser.h"
#import "CYLoginHttpTool.h"
#import "CYJsonInfo.h"
#import "MJExtension.h"
#import "CYMeTool.h"
#import "MBProgressHUD+MJ.h"
#import "CYABTool.h"
#import "CYCloudPerson.h"
#import "CYDatabase.h"
#import "CYCreditTool.h"

@interface CYCloudSyn ()

@property (weak, nonatomic) IBOutlet CircleView *circlesView;
@property (weak, nonatomic) IBOutlet UIView *dynamicCircleView;
@property (weak, nonatomic) IBOutlet UILabel *localPersonCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *netPersonCount;
@property (weak, nonatomic) IBOutlet UIButton *copysBtn;
@property (weak, nonatomic) IBOutlet UIButton *synBtn;
@property (weak, nonatomic) IBOutlet UILabel *TooltipLabel;
@property (weak, nonatomic) IBOutlet UILabel *newlyTimeLable;

@end

@implementation CYCloudSyn

- (void)viewDidLoad {
     [super viewDidLoad];
     [self setupNavigationView];
     [self addCircleView];
     [self initView];
     //    [self loadData];
     self.title = @"云同步";
}

- (void)initView {
     self.view.backgroundColor = [UIColor whiteColor];
     self.copysBtn.backgroundColor = CYNaviThemeColor;
     self.synBtn.backgroundColor = CYNaviThemeColor;
     self.TooltipLabel.textColor = CYNaviThemeColor;
}

- (void)addCircleView {
     self.circlesView.strokeColor = CYNaviThemeColor;
     [self.circlesView setStrokeEnd:1.f animated:YES];
}

- (void)loadData {
     //获取已备份的人数
     CYUser *user = [CYLoginHttpTool  userData].user;
     [CYHttpTool getWithURL:[CYURL getCurrentContacts] params:@{@"userId": user.userId} success:^(id json) {
          CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
          if (jsonInfo.isSuccess) {
               NSDictionary *data = jsonInfo.message;
               if (data[@"currentNumber"]) {
                    self.netPersonCount.text = CYStringFormat(@"网络联系人：%@条", data[@"currentNumber"]);
               } else {
                    self.netPersonCount.text = CYStringFormat(@"网络联系人：%@条", @(0));
               }
          } else {
               self.netPersonCount.text = CYStringFormat(@"网络联系人：%@条", @(0));
          }
     } failure:^(NSError *error) {
          CYLog(@"获取最新网络联系人数失败: %@", error);
     }];
     
     //获取时间节点
     [CYHttpTool postWithURL:[CYURL getNewVersionTime] params:@{@"userId":user.userId} success:^(id json) {
          CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
          if (jsonInfo.isSuccess) {
               NSDictionary *messageDic = jsonInfo.message;
               NSString *time = messageDic[@"time"];
               if (time.length < 10) {
                    self.newlyTimeLable.text = @"最近一次备份：您还没有备份过";
               } else {
                    self.newlyTimeLable.text = CYStringFormat(@"最近一次备份：%@", time);
               }
               //            _versioncp = messageDic[@"time"];
               //        CYLog(@"versoncp = %@",_versioncp);
          }
     } failure:^(NSError *error) {
          [MBProgressHUD showError:@"备份错误"];
     }];
     
     if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized) return;
     RHAddressBook *ab = [CYABTool addressBook];
     NSArray *allpeople = ab.people;
     self.localPersonCountLabel.text =CYStringFormat(@"本地联系人：%lu条", (unsigned long)allpeople.count);
}

#pragma mark -

- (IBAction)copysBtn:(UIButton *)sender {
     
     UIAlertView *notice = [[UIAlertView alloc]initWithTitle:@"提示" message:@"为了让您更好的管理通讯录，我们将把您的通讯录信息备份至服务器" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
     notice.delegate = self;
     
     [notice show];
     
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
     if (buttonIndex == 0) {//取消
     }else if (buttonIndex == 1){
          //        sender.enabled = NO;
          //        sender.backgroundColor = [UIColor grayColor];
          @try {
               CircleView *ciView = (CircleView *)self.dynamicCircleView;
               ciView.strokeColor = [UIColor orangeColor];
               self.TooltipLabel.text = @"备份中";
               CYUser *user = [CYLoginHttpTool  userData].user;
               if (user) {
                    //云同步
                    [CYMeTool cloudSynWithSuccess:^(id json) {
                         self.TooltipLabel.text = @"备份成功";
                         //                    sender.enabled = YES;
                         //                    sender.backgroundColor = CYNaviThemeColor;
                         //                    NSString *size = json[@"message"][@"netSize"];
                         //                    self.netPersonCount.text = CYStringFormat(@"网络联系人：%@条", size);
                         //                    self.newlyTimeLable.text = CYStringFormat(@"最近一次备份：%@", [CYCreditTool timeWithDate:[NSDate date] formatter:CYTimeFormatYMDHmsType]);
                    } failure:^(NSError *error) {
                         CYLog(@"云同步: %@", error);
                         //                    [self reportError:error];
                         self.TooltipLabel.text = @"备份失败";
                         //                    sender.enabled = YES;
                         //                    sender.backgroundColor = CYNaviThemeColor;
                    } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
                         CGFloat totalWritten = totalBytesWritten;
                         CGFloat totalToWrite = totalBytesExpectedToWrite;
                         CGFloat scale = totalWritten/totalToWrite;
                         
                         self.TooltipLabel.text = CYStringFormat(@"%.1f%%", scale*100);
                         [ciView setStrokeEnd:scale animated:YES];
                    }];
               } else {
                    self.TooltipLabel.text = @"无可用数据";
                    //                sender.enabled = YES;
                    //                sender.backgroundColor = CYNaviThemeColor;
               }
          }
          @catch (NSException *exception) {
               [self reportException:exception reason:@"云备份失败"];
               self.TooltipLabel.text = @"备份失败";
               //            sender.enabled = YES;
               //            sender.backgroundColor = CYNaviThemeColor;
          }
          
     }
     
     
}



#pragma mark - 恢复
- (IBAction)synBtn:(UIButton *)sender {
     @try {
          sender.enabled = NO;
          sender.backgroundColor = [UIColor grayColor];
          
          CYUser *user = [CYLoginHttpTool  userData].user;
          self.TooltipLabel.text = @"恢复中";
          //处理数据
          [CYHttpTool postWithURL:[CYURL getContactsByUserId] params:@{@"userId":user.userId} success:^(id json) {
               sender.enabled = YES;
               sender.backgroundColor = CYNaviThemeColor;
               CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
               if (jsonInfo.isSuccess) {
                    //处理数据开始
                    NSArray *personArr = jsonInfo.message;
                    //将变更过的联系人
                    NSArray *contactsArr = [CYMeTool contactsArr];
                    [self deletePersons:contactsArr];
                    NSArray *addList = personArr;//新增加的联系人
                    [self addPersons:addList];
                    self.TooltipLabel.text = @"恢复成功";
                    
               }
               else {
                    [MBProgressHUD hideHUDForView:self.view];
                    //恢复失败提示
                    CYAlertView(@"恢复失败，请稍候再试");
                    sender.enabled = YES;
                    sender.backgroundColor = CYNaviThemeColor;
               }
               
          } failure:^(NSError *error) {
               [MBProgressHUD hideHUDForView:self.view];
               CYAlertView(@"网络连接失败，请稍候再试");
               CYLog(@"%@", error);
          }];
     }
     @catch (NSException *exception) {
          self.TooltipLabel.text = @"恢复失败";
          [self reportException:exception reason:@"云恢复失败"];
     }
}

/**
 *  新增联系人
 *
 *  @param addList
 *
 *  @return
 */
- (BOOL)addPersons:(NSArray *)addList {
     NSMutableArray *addListModel = [NSMutableArray array];
     [addList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
          CYCloudPerson *person = [CYCloudPerson objectWithKeyValues:obj];
          [addListModel addObject:person];
     }];
     //添加数据到通讯录
     [CYMeTool addABPersons:addListModel success:^(NSArray *arr) {
          //        CYAlertView(CYStringFormat(@"云同步新增：%lu条数据", (unsigned long)arr.count));
          //        self.localPersonCountLabel.text = [NSString stringWithFormat:@"此次已恢复人数: %lu",((unsigned long)arr.count)];
          //        _tmlb.text = [NSString stringWithFormat:@"当前恢复节点:%@",_versiongt];
          
     } failure:^(NSArray *arr) {
          //        CYAlertView(CYStringFormat(@"云同步新增失败：%lu条数据", (unsigned long)arr.count));
     }];
     return YES;
}

/**
 *  删除联系人
 *
 *  @param deleteList
 *
 *  @return
 */
- (BOOL)deletePersons:(NSArray *)deleteList {
     NSMutableArray *deleteListModel = [NSMutableArray array];
     [deleteList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
          CYCloudPerson *person = [CYCloudPerson objectWithKeyValues:obj];
          [deleteListModel addObject:person];
     }];
     //删除通讯录数据
     [CYMeTool deleteABPerson:deleteListModel success:^(NSArray *arr) {
          //        CYAlertView(CYStringFormat(@"云同步删除：%lu条数据", (unsigned long)arr.count));
          //删除收藏中的存在的记录
          BOOL result = [[CYDatabase sharedDatabase] deleteCollectionsWithPersons:arr];
          CYLog(@"收藏删除是否成功: %d", result);
          
     } failure:^(NSArray *arr) {
          //        CYAlertView(CYStringFormat(@"云同步删除失败：%lu条数据", (unsigned long)arr.count));
     }];
     return YES;
}
@end
